﻿Ext.onReady(function () {
    Ext.QuickTips.init();
    var addForm;
    var newwin;
    var eventID;
    // create the Data Store
    var store = Ext.create('Ext.data.Store', {
        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: {   //ScriptTagProxy
            type: 'ajax',
            url: '../../Handlers/logMaster_Data.aspx'
        },

        // create reader that reads the Topic records
        reader: {
            root: 'data',
            totalProperty: 'totalCount',
            id: 'ID',
            fields: [
                'ID', 'OperationType', 'TableName', 'BusinessesName', 'Content',
                { name: 'CreateTime', type: 'string' },
                , 'User_ID', 'IP', 'Location', 'Browser'
            ]
        },

        // turn on remote sorting
        remoteSort: true
    });
    store.setDefaultSort('ID', 'desc');

    function renderDateTime(value) {
        var tmpValue = value.replace(/@/g, "");
        if (tmpValue * 1 < 0) return "";
        var tmpDate = new Date(tmpValue * 1);
        return String.format('{0}', Ext.util.Format.date(tmpDate, 'Y/m/d'));
    }

    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    // var nm = new Ext.grid.RowNumberer(); 
    var sm = Ext.create('Ext.grid.CheckboxSelectionModel'); // add checkbox column
    var cm = Ext.create('Ext.grid.ColumnModel',[sm, {
        id: 'ID', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
        header: "序号",
        dataIndex: 'ID',
        align: 'center',
        width: 60
    }, {
        header: "操作类型",
        dataIndex: 'OperationType',
        width: 200
    }, {
        header: "操作的表",
        dataIndex: 'TableName',
        align: 'center',
        width: 60
    }, {
        header: "操作内容",
        dataIndex: 'Content',
        align: 'center',
        width: 60
    }, {
        header: "操作用户ID",
        dataIndex: 'User_ID',
        align: 'center',
        width: 60
    }, {
        header: "创建时间",
        dataIndex: 'CreateTime',
        width: 60,
        align: 'center',
        renderer: Ext.util.Format.dateRenderer('Y/m/d')
    }, {
        header: "IP",
        dataIndex: 'IP',
        width: 60,
        align: 'center'
    }, {
        header: "地点",
        dataIndex: 'Location',
        width: 60,
        align: 'center'
    }, {
        header: "浏览器",
        dataIndex: 'Browser',
        width: 60,
        align: 'center'
    }
    ]);
    cm.defaultSortable = true;

    // by default columns are sortable
    var grid = Ext.create('Ext.grid.GridPanel',{
        el: 'topic-grid',
        width: 750,
        height: 500,
        title: '日志管理',
        store: store,
        cm: cm,
        sm: sm,
        trackMouseOver: false,
        //sm: new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),
        loadMask: true,
        autoShow: true,
        viewConfig: {
            forceFit: true,
            enableRowBody: true,
            showPreview: true,
            getRowClass: function (record, rowIndex, p, store) {
                if (this.showPreview) {
                    p.body = '<p>　　　　　　详细：</p>';
                    return 'x-grid3-row-expanded';
                }
                return 'x-grid3-row-collapsed';
            }
        },
        bbar: new Ext.PagingToolbar({
            pageSize: 25,
            store: store,
            displayInfo: true,
            displayMsg: '当前显示{0} - {1}条，总共{2}条',
            emptyMsg: "没有数据可以显示",
            items: [
                '-', {
                    pressed: true,
                    enableToggle: true,
                    text: '详细',
                    iconCls: 'preview',
                    toggleHandler: toggleDetails
                }]
        }),
        tbar: [{
            id: 'SEARCH',
            text: ' 查询  ',
            tooltip: '日志查询',
            iconCls: 'search'
        }, '-', {
            text: '删除',
            tooltip: '日志删除',
            iconCls: 'remove',
            handler: showDelMess
        }]
    });

    // render it
    grid.render();
    //Double Click　イベント

    grid.on("rowdblclick", function (grid) {
        loadFormData(grid);
    });
    var loadFormData = function (grid) {
        var _record = grid.getSelectionModel().getSelected();
        if (!_record) {
            Ext.example.msg('提示', '记录加载失败！');
        } else {

            myFormWin();

            addForm.getForm().load({
                url: '../../Handlers/logMaster_Data.aspx?event=show',
                waitMsg: '正在查询，请稍候..',

                failure: function () {
                    Ext.MessageBox.show({
                        title: '提示',
                        msg: '记录加载失败!',
                        buttons: Ext.Msg.OK,
                        icon: Ext.MessageBox.ERROR
                    });
                },
                success: function () {
                    eventID = "edit";
                    //Ext.MessageBox.alert('メッセージ', 'データ読取成功！');
                }
            });
        }
    }


    // trigger the data store load
    store.load({ params: { start: 0, limit: 25 } });

    function toggleDetails(btn, pressed) {
        var view = grid.getView();
        view.showPreview = pressed;
        view.refresh();
    }

    //Detail Combox
    var storeDept = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: "../../Handlers/logMaster_Data.aspx"
        }),
        // create reader that reads the project records
        reader: new Ext.data.JsonReader({ root: 'data' }, [
            { name: 'User_ID', type: 'string' },
            { name: 'OperationType', type: 'string' }
        ])
    });
    storeDept.load();

    var storeStatus = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: "../../Handlers/logMaster_Data.aspx"
        }),
        // create reader that reads the project records
        reader: new Ext.data.JsonReader({ root: 'data' }, [
            { name: 'User_ID', type: 'string' },
            { name: 'OperationType', type: 'string' }
        ])
    });
    storeStatus.load();

    var storeUser = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: "../../Handlers/logMaster_Data.aspx"
        }),
        // create reader that reads the project records
        reader: new Ext.data.JsonReader({ root: 'data' }, [
            { name: 'User_ID', type: 'string' },
            { name: 'OperationType', type: 'string' }
        ])
    });
    storeUser.load();

    //********************ADD Page JS**********************//
    // create reader that reads the Topic records
    var jsonFormReader = Ext.create('Ext.data.JsonReader',{
        root: 'data',
        totalProperty: 'totalCount',
        id: 'ID',
        fields: [
                'ID', 'OperationType', 'TableName', 'BusinessesName', 'Content',
                { name: 'CreateTime', type: 'string' },
                , 'User_ID', 'IP', 'Location', 'Browser'
        ]
    });

    addForm = Ext.create('Ext.FormPanel',{
        labelWidth: 75, // label settings here cascade unless overridden
        //url : 'prjMaster_Data.aspx',
        frame: true,
        title: '添加',
        width: 580,
        waitMsgTarget: true,
        reader: jsonFormReader,
        defaults: {
            width: 580
        },
        items: [{
            layout: 'column',
            border: false,
            items: [{
                columnWidth: .5,
                layout: 'form',
                border: false,
                items: [{
                    xtype: 'textfield',
                    fieldLabel: '&nbsp;&nbsp;&nbsp;&nbsp;序号',
                    labelStyle: 'width:80px',
                    width: 150,
                    name: 'ID',
                    allowBlank: false,
                    blankText: '序号是必填项'
                }, new Ext.form.ComboBox({
                    fieldLabel: '&nbsp;&nbsp;&nbsp;&nbsp;操作类型',
                    labelStyle: 'width:80px',
                    width: 150,
                    name: 'OperationType',
                    store: storeDept,
                    displayField: 'OperationType',
                    valueField: 'OperationType',
                    hiddenName: 'OperationType',
                    mode: 'client',
                    triggerAction: 'all',
                    emptyText: '操作类型为空',
                    selectOnFocus: true
                }), new Ext.form.DateField({
                    fieldLabel: '&nbsp;&nbsp;&nbsp;&nbsp;操作日期',
                    labelStyle: 'width:80px',
                    width: 150,
                    format: 'Y/m/d',
                    name: 'CreateTime',
                    reader: renderDateTime,
                    beforerender: renderDateTime

                }),
                        new Ext.form.ComboBox({
                            fieldLabel: '&nbsp;&nbsp;&nbsp;&nbsp;操作类型',
                            labelStyle: 'width:80px',
                            width: 150,
                            name: 'OperationType',
                            store: storeStatus,
                            displayField: 'OperationType',
                            valueField: 'OperationType',
                            hiddenName: 'OperationType',
                            mode: 'client',
                            triggerAction: 'all',
                            emptyText: '操作类型为空',
                            selectOnFocus: true
                        })
                ]
            }, {
                columnWidth: .5,
                layout: 'form',
                border: false,
                items: [{
                    xtype: 'textfield',
                    fieldLabel: '&nbsp;&nbsp;&nbsp;&nbsp;操作类型',
                    labelStyle: 'width:80px',
                    width: 150,
                    name: 'OperationType',
                    allowBlank: false,
                    blankText: '操作类型为必填项'
                }, new Ext.form.ComboBox({
                    fieldLabel: '&nbsp;&nbsp;&nbsp;&nbsp;操作类型',
                    labelStyle: 'width:80px',
                    width: 150,
                    name: 'OperationType',
                    store: storeUser,
                    displayField: 'OperationType',
                    valueField: 'OperationType',
                    hiddenName: 'OperationType',
                    mode: 'client',
                    triggerAction: 'all',
                    emptyText: '操作类型为必填项',
                    selectOnFocus: true
                }), new Ext.form.DateField({
                    fieldLabel: '&nbsp;&nbsp;&nbsp;&nbsp;操作类型',
                    labelStyle: 'width:80px',
                    width: 150,
                    format: 'Y/m/d',
                    name: 'OperationType'
                })
                ]
            }]
        }, {
            xtype: 'textarea',
            name: 'OperationType',
            fieldLabel: '&nbsp;&nbsp;&nbsp;&nbsp;详细',
            labelStyle: 'width:80px',
            height: 150,
            width: 170,
            anchor: '90%'
        }
        ],
        buttons: [{
            id: 'btnSave',
            text: '保 存',
            handler: doSave,
            disabled: false
        }, {
            text: '保存成功',
            handler: function () {
                newwin.hide();
            }
        }]
    });
    var myFormWin = function () {
        showAddPanel();
    }
    function showAddPanel() {
        if (!newwin) {
            newwin = new Ext.Window({

                //el : 'topic-win',
                layout: 'fit',
                width: 600,
                height: 380,
                closeAction: 'hide',
                closable: true,
                plain: true,
                modal: 'true',
                title: '窗口',
                items: addForm
            });

        }

        newwin.show('New1');
    }
    function doSave() {
        var evt = eventID;

        Ext.MessageBox.show({
            msg: '正在处理中…',
            progressText: '正在处理中…',
            width: 200,
            wait: true,
            waitConfig: { interval: 200 },
            icon: 'ext-mb-save',
            nimEl: 'btnSave'
        });
        addForm.getForm().submit({
            url: '../../Handlers/logMaster_Data.aspx?event=' + evt,
            method: 'POST',
            success: function (form, action) {
                Ext.MessageBox.hide();
                Ext.MessageBox.alert('提示', '处理完了！');
                newwin.hide();
                //store.load({params:{start:0, limit:25}});
                store.reload();
            },
            failure: function (form, action) {
                Ext.MessageBox.hide();
                Ext.MessageBox.show({
                    title: '提示',
                    msg: '处理完了！',
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.ERROR
                });
            }
        });
    }

    function showDelMess() {
        Ext.MessageBox.confirm('提示', '处理完了', doDel);
    }
    function doDel(btn) {
        if (btn == 'yes') {
            var row = grid.getSelections();
            var jsonData = "";
            for (var i = 0, len = row.length; i < len; i++) {
                var ss = row[i].get("ID");
                jsonData = jsonData + ss + ",";
            }
            if (jsonData.length == 0) {
                Ext.MessageBox.alert('提示', '处理完了');
            } else {
                Ext.lib.Ajax.request(
                            'GET',
                            '../../Handlers/logMaster_Data.aspx?event=delete&delData=' + jsonData,
                            {
                                success: function (form, action) {
                                    Ext.MessageBox.alert('メッセージ', '削除しました。');
                                    store.reload();
                                },
                                failure: function (form, action) {
                                    Ext.MessageBox.show({
                                        title: 'エラー',
                                        msg: '削除でエラーが発生しました。管理者までご連絡ください！',
                                        buttons: Ext.Msg.OK,
                                        icon: Ext.MessageBox.ERROR
                                    });
                                }
                            },
                            null
                        );

            }
        }

    }
});